package org.example.novel.config;

import org.example.novel.annotation.Anonymous;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Configuration
public class AnonymousConfig extends RequestMappingHandlerMapping {

    public static final Map<String,ArrayList<String>> map = new ConcurrentHashMap<>();

    @Bean
    public void init(){
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = getHandlerMethods();
        handlerMethods.forEach((info,method)->{
            Anonymous annotation = method.getMethod().getAnnotation(Anonymous.class);
            if (annotation!=null){
                Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
                Set<String> patterns = info.getPatternsCondition().getPatterns();
                List<String> methodCollect = methods.stream().map(Enum::name).collect(Collectors.toList());
                List<String> urlCollect = new ArrayList<>(patterns);
                if (map.containsKey(methodCollect.get(0))){
                    ArrayList<String> strings = map.get(methodCollect.get(0));
                    extracted(methodCollect, urlCollect, strings);
                }else{
                    ArrayList<String> strings = new ArrayList<>();
                    extracted(methodCollect, urlCollect, strings);
                }
            }
        });
        map.forEach((k,v)->{
            System.out.println(k+"------"+v);
        });
    }

    private void extracted(List<String> methodCollect, List<String> urlCollect, ArrayList<String> strings) {
        if (isaBoolean(urlCollect)){
            String s = urlCollect.get(0).split("\\{")[0] + "**";
            strings.add(s);
            map.put(methodCollect.get(0), strings);
        }else{
            strings.add(urlCollect.get(0));
            map.put(methodCollect.get(0), strings);
        }
    }

    private static boolean isaBoolean(List<String> urlCollect) {
        return urlCollect.get(0).split("\\{").length > 1;
    }

}
